package com.house.controller;


import com.house.entity.House;
import com.house.entity.Order;
import com.house.entity.Result;
import cn.dev33.satoken.stp.StpUtil;
import com.house.service.HouseService;
import com.house.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    private HouseService houseService;
    // 租客提交预约申请
    @PostMapping("/appointment")
    public Result<String> createAppointment(@RequestBody Order order) {
        // 从 Sa-Token 获取当前租客 ID
        Long tenantId = StpUtil.getLoginIdAsLong();
        order.setTenantId(tenantId);

        // 验证房源是否存在
        House house = houseService.getHouseById(order.getHouseId());
        if (house == null) {
            return Result.error("房源不存在");
        }

        // 设置房东 ID 和其他信息
        order.setLandlordId(house.getLandlordId());
        order.setStatus("PENDING");
        order.setPrice(house.getPrice()); // 自动关联租金
        orderService.createAppointment(order);

        return Result.success("预约申请提交成功");
    }


    // 房东确认或拒绝预约
    @PostMapping("/appointment/confirm")
    public Result<String> confirmAppointment(@RequestParam Long orderId, @RequestParam String status) {
        // 获取当前登录房东 ID
        Long landlordId = StpUtil.getLoginIdAsLong();

        // 验证订单是否存在且房东有权限操作
        Order order = orderService.getOrderById(orderId);
        if (order == null || !order.getLandlordId().equals(landlordId)) {
            return Result.error("无权限操作该订单或订单不存在");
        }

        // 更新订单状态
        orderService.updateOrderStatus(orderId, status);
        return Result.success("预约状态更新成功");
    }


    // 租客支付订单
    @PostMapping("/pay")
    public Result<String> payOrder(@RequestParam Long orderId) {
        // 获取当前登录租客 ID
        Long tenantId = StpUtil.getLoginIdAsLong();

        // 验证订单是否存在且租客有权限支付
        Order order = orderService.getOrderById(orderId);
        if (order == null || !order.getTenantId().equals(tenantId)) {
            return Result.error("无权限支付该订单或订单不存在");
        }

        // 更新订单状态为已支付
        orderService.payOrder(orderId);
        return Result.success("支付成功");
    }


    // 获取租客的订单列表
    @GetMapping("/tenant/orders")
    public Result<List<Order>> getTenantOrders() {
        Long tenantId = StpUtil.getLoginIdAsLong();
        return Result.success(orderService.getOrdersByTenant(tenantId));
    }

    // 获取房东的订单列表
    @GetMapping("/landlord/orders")
    public Result<List<Order>> getLandlordOrders() {
        Long landlordId = StpUtil.getLoginIdAsLong();
        return Result.success(orderService.getOrdersByLandlord(landlordId));
    }
}

